import { useEffect, useRef, useState } from "react";
import dayjs from "dayjs";
import Taro,{useDidShow} from "@tarojs/taro";
import { Image, ScrollView, Text, View } from "@tarojs/components";
import { AtActionSheet, AtModal } from "taro-ui";
import GoodsItem from "@/components/GoodsItem";
import { RoundNum } from "@/utils/Tools";
import YiCode from '@/components/yi-code'
import ActivityModal from "./activityModal";
import './index.scss'

export default () => {
  const { router } = Taro.getCurrentInstance()
  const [order, setOrder] = useState({
    ticketList: []
  })
  const [showActivity,setShowActicity] = useState(false)
  const [goodsList, setGoodsList] = useState([])
  const [expireTime, setExpireTime] = useState('')
  const [goodsCount, setGoodsCount] = useState({})
  const [goodsTotalCount, setGoodsTotalCount] = useState(0)
  const [priceMap, setPriceMap] = useState({
    totalPrice: 0,
    ticketPrice: 0,
    goodsPrice: 0
  })
  const couponRef = useRef({})
  const [curCoupon,setCurCoupon] = useState([])
  const [selectGoodsCoupon,setSelectGoodsCoupon] = useState([])
  const [curCard,setCurCard] = useState({})
  const [rebook,setRebook] = useState({})
  const [showModal,setShowModal] = useState(false)
  const [showRebook,setShowRebook] = useState(false)
  const [captcha,setCaptcha] = useState('')
  const [messageInfo,setMessageInfo] = useState('')

  useEffect(() => {
    const fetchData = async e=>{
      const orderId = router.params.id
      const infoData = await Taro.$get('/cinema-app/api/v1/order', {
        orderId
      })
      Taro.$post('/cinema-app/api/v1/refund/byCinemaId',{
        "cinemaId": infoData.content?.cinemaId,
        "showTimeStart":infoData.content?.showTimeStart
      }).then(ret=>{
        setRebook(ret.content)
      })
      if (infoData.code == '1') {
        infoData.content.showTimeStart = getShowDate(infoData.content.ticketList[0].showTimeStart) + '-' + dayjs(infoData.content.ticketList[0].showTimeEnd).format("HH:mm")
        infoData.content.ticketPrice = infoData.content.ticketList?.reduce((acc, cur) => acc + parseFloat(cur.ticketPrice), 0)
        setOrder(infoData.content)
        if(infoData.content?.goodsList?.length){
          const _goodsList = infoData.content.goodsList || []
          const map = {}
          _goodsList.forEach(item => {
            if (!map[item.goodsId]) {
              map[item.goodsId] = 1
            } else {
              map[item.goodsId] += 1
            }
          })
          setGoodsCount(map)
        }
        setPriceMap({
          totalPrice: infoData.content.payAmount,
          ticketPrice: infoData.content.ticketList?.reduce((acc, cur) => acc + parseFloat(cur.payAmount), 0)
        })
        let et = infoData.content.expireTime
        let timer = setInterval(() => {
          const r = --et
          if (r <= 0) {
            clearInterval(timer)
            Taro.navigateBack()
          } else {
            setExpireTime(`${(Math.floor(r / 60) + '').padStart(2, '0')}:${((r % 60) + '').padStart(2, '0')}`)
          }
        }, 1000)
      }else{
        Taro.$toast(infoData.message)
        setTimeout(() => {
          Taro.navigateBack()
        }, 1000);
      }
      const firstRes = await Taro.$get('/cinema-app/api/v1/cinema/suggest/list', {
        cinemaId: Taro.getStorageSync('selectMerchant').id,
        typeId: 1
      });
      if (firstRes.code == '1') {
        setGoodsList(firstRes.content);
      }
      Taro.eventCenter.off('changeCoupon')
      Taro.eventCenter.on('changeCoupon', async (data)=>{
        if(data.ticket){
          couponRef.current = {...couponRef.current,ticket:data.ticket}
          setCurCoupon(data.ticket)
          if(data.ticket[0]?.voucherType == '4'){
            setCurCard({})
          }
        }
        if(data.goods){
          couponRef.current = {...couponRef.current,goods:data.goods}
          setSelectGoodsCoupon(data.goods)
        }
        const res = await handleCalcPrice(data)
        if(res.code == '1'){
          setPriceMap({
            totalPrice: res.content.payAmount,
            ticketPrice: res.content.ticketList?.reduce((acc, cur) => acc + parseFloat(cur.payAmount), 0)
          })
        }else{
          setTimeout(() => {
            Taro.$toast(res.message || '提交失败')
          }, 500);
          if(data.ticket){
            couponRef.current = {...couponRef.current,ticket:[]}
            setCurCoupon([])
          }
          if(data.goods){
            couponRef.current = {...couponRef.current,goods:[]}
            setSelectGoodsCoupon([])
          }
        }
      })
      Taro.eventCenter.off('changeCard')
      Taro.eventCenter.on('changeCard', async (data)=>{
        if(data.curCard){
          setCurCard(data.curCard)
          if(data.curCard.isDxCard == '1'){
            data.goods = []
            data.ticket = []
            couponRef.current = {...couponRef.current,ticket:[],goods:[]}
            setCurCoupon([])
            setSelectGoodsCoupon([])
          }
        }else{
          setCurCard({})
        }
        const res = await handleCalcPrice(data)
        if(res.code == '1'){
          setPriceMap({
            totalPrice: res.content.payAmount,
            ticketPrice: res.content.ticketList?.reduce((acc, cur) => acc + parseFloat(cur.payAmount), 0)
          })
        }else{
          setTimeout(() => {
            Taro.$toast(res.message || '提交失败')
          }, 500);
          setCurCard({})
        }
      })
    }
    fetchData()
  },[]);

  useEffect(() => {
    setGoodsTotalCount(Object.values(goodsCount)?.reduce((acc, cur) => acc + cur, 0))
  }, [goodsCount])
  
  const getShowDate = (date) => {
    const weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const d = dayjs(date)
    return `${d.format('MM月DD日')}（${weekList[d.day()]}）${d.format('HH:mm')}`
  }

  const changeGoods = (goodsId, count) => {
    Taro.showLoading({ title: '加载中...' })
    Taro.$post('/cinema-app/api/v1/order/addGoods', [
      {
        goodsCount: count,
        goodsId,
        orderId: router.params.id
      }
    ],'1').then(async res => {
      Taro.hideLoading()
      if (res.code == '1') {
        const _goodsList = res.content.goodsList || []
        const result = await handleCalcPrice()
        setOrder({
          ...order,
          goodsList: _goodsList,
          payAmount: result.content.payAmount
        })
        const map = {}
        _goodsList.forEach(item => {
          if (!map[item.goodsId]) {
            map[item.goodsId] = 1
          } else {
            map[item.goodsId] += 1
          }
        })
        setGoodsCount(map)
        setPriceMap({
          ...priceMap,
          totalPrice: result.content.payAmount,
          goodsPrice: _goodsList?.reduce((acc, cur) => acc + parseFloat(cur.payAmount), 0)
        })
      }
    })
  }
  async function handleCalcPrice(values){  ///  锁定优惠券计算价格
    let ticketCoupon = values?.ticket || couponRef.current.ticket
    let goodsCoupon = values?.goods || couponRef.current.goods
    let selectCard = values?.curCard || curCard
    const data = {
      orderId: router.params.id,
      cinemaId:Taro.getStorageSync('merchantId'),
      filmCouponIdList:[],
      goodsCouponIdList:[]
    }
    if(ticketCoupon?.length){
      ticketCoupon.map(res=>{
        data.filmCouponIdList.push(res.id)
      })
    }
    if(goodsCoupon?.length){
      goodsCoupon.map(res=>{
        data.goodsCouponIdList.push(res.id)
      })
    }
    if(selectCard.id){
      data.memberCardNo = selectCard.id
    }
    Taro.showLoading({title:'加载中...'})
    return await Taro.$post('/cinema-app/api/v1/order/pricing',data,'1')
  }

  const pay = () => {
    Taro.showLoading({ title: '加载中...' })
    const data = {
      orderId: router.params.id,
      cinemaGovCode:Taro.getStorageSync('selectMerchant').cinemaGovCode,
      filmCouponIdList:[],
      goodsCouponIdList:[]
    }
    if(couponRef.current.ticket?.length){
      couponRef.current.ticket.map(res=>{
        data.filmCouponIdList.push(res.id)
      })
    }
    if(couponRef.current.goods?.length){
      couponRef.current.goods.map(res=>{
        data.goodsCouponIdList.push(res.id)
      })
    }
    if(curCard.id){
      data.memberCardNo = curCard.id,
      data.cardPassword = captcha
    }
    Taro.$post('/cinema-app/api/v1/order/push', data, '1').then(res => {
      if (res.code != '1') {
        Taro.$toast(res.message)
        return
      }
      if(curCard.id && curCard.isDxCard == '1'){
        Taro.redirectTo({
          url: `/mainPages/payResult/index?id=${res.content.orderId}`
        })
        return;
      }
      if (res.content?.needPay) {
        handlePay(res.content.orderId)
      } else {
        Taro.redirectTo({
          url: `/mainPages/payResult/index?id=${res.content.orderId}`
        })
      }
    })
  }
  const handlePay = async (e)=>{    /// 点击去支付
    Taro.showLoading({
      title:'加载中...'
    })
    const data = {
      appId:Taro.$mpAppid,
      openId:await Taro.getOpenId(),
      orderId:e
    }
    Taro.$post('/order/users/orders/pay',data,'1').then(ret=>{
      if(ret.code == '1'){
        let {content} = ret
        if(process.env.TARO_ENV == 'tt'){
          tt.pay({
            orderInfo: {
              order_id:content.data.orderId,
              order_token: content.data.orderToken
            },
            service: 5,
            _debug:1,
            success:res=>{
              if(res.code == 0){
                Taro.redirectTo({
                  url:`/mainPages/payResult/index?id=${data.orderId}`
                })
              }
            },
            fail:err=>{
              uni.showToast({
                title:'支付失败',
                icon:'none'
              })
            }
          });
          return;
        }
        if(process.env.TARO_ENV == 'h5' && navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger"){
          WeixinJSBridge.invoke('getBrandWCPayRequest', {
            "appId": Taro.$mpAppid,
            "timeStamp": content.timeStamp,   
            "nonceStr": content.nonceStr,  
            "package": content.packageStr,
            "signType": content.signType,    
            "paySign":content.paySign
          },(result) => {
            if(result.err_msg == "get_brand_wcpay_request:cancel"){
              Taro.showToast({
                title:'取消支付',
                icon:'error'
              })
            }else{
              Taro.redirectTo({
                url:`/mainPages/payResult/index?id=${data.orderId}`
              })
            }
          });
          return;
        }
        Taro.requestPayment({
          timeStamp: content.timeStamp,
          nonceStr: content.nonceStr,
          package: content.package,
          signType: content.signType,
          paySign: content.paySign,
          success:res=>{
            Taro.redirectTo({
              url:`/mainPages/payResult/index?id=${data.orderId}`
            })
          },
          fail:err=>{
            Taro.showToast({
              title:'支付失败',
              icon:'none'
            })
          }
        })
      }else{
        Taro.showToast({
          title:ret.message,
          icon:'none'
        })
      }
    })
  }

  return (
    <View className='confirm-order'>
      <View className='page-content'>
        <View className='part-1'>
          <View className='time flex-cc'>{expireTime}</View>
          <View className='row-1 flex-cs'>
            <Image className='col-1' src={order.filmPosterUrl}></Image>
            <View className='col-2'>
              <View>
                <View className='r-1'>{order.filmNickName}</View>
              </View>
              <View>
                <View className='r-2'>{order.showTimeStart}</View>
                <View className='r-3'>{order.cinemaName}</View>
                <View className='r-4'>{(order.ticketList[0] || {}).hallNickName}  ｜  {order.ticketList.map(item => `${item.seatRow}排${item.seatColumn}座`).join('  ')}</View>
                <View className='r-5'>{order.ticketList.length}张 原价 ¥{order.ticketPrice}</View>
              </View>
            </View>
          </View>
          <Image src={require('@/static/separator.png')} mode='aspectFill' className="row-img" />
          <View className='row-2'>
            <View className='col-1 flex-cs'>
              <View className='item flex-cs'>
                <Image className='i-1' src={require(`@/images/ticket/${rebook.supportTicket=='1'?'dui':'no'}.png`)}></Image>
                <Text className='i-2'>{rebook.supportTicket=='1'?'支持退票':'不支持退票'}</Text>
              </View>
              <View className='item flex-cs'>
                <Image className='i-1' src={require(`@/images/ticket/${rebook.supportRescheduling=='1'?'dui':'no'}.png`)}></Image>
                <Text className='i-2'>{rebook.supportRescheduling=='1'?'支持改签':'不支持改签'}</Text>
              </View>
            </View>
            <View className='col-2 flex-cs' onClick={()=>{setShowRebook(true)}}>
              <Text className='i-1'>退改签须知</Text>
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
        </View>
        <AtActionSheet className="rebook-modal" title='退改签详情' isOpened={showRebook} onClose={()=>{setShowRebook(false)}}>
          <View className="modal-main">
            <View className="modal-h2">
              <Image className='img' src={require(`@/images/ticket/${rebook.supportTicket=='1'?'dui':'no'}.png`)}></Image>
              <Text className='title'>{rebook.supportTicket=='1'?'限时退票':'不支持退票'}</Text>
              <View className="at-icon at-icon-chevron-right"></View>
            </View>
            {rebook.supportTicket=='1'?rebook.memberRuleDesc?.map(res=>{
              return <View className="modal-p" key={res}>{res}</View>
            }):null}
            <View className="modal-h2">
              <Image className='img' src={require(`@/images/ticket/${rebook.supportRescheduling=='1'?'dui':'no'}.png`)}></Image>
              <Text className='title'>{rebook.supportRescheduling=='1'?'限时改签':'不支持改签'}</Text>
              <View className="at-icon at-icon-chevron-right"></View>
            </View>
          </View>
        </AtActionSheet>
        {/* <View className='part-2 flex-cs'>
         <View className='flex-cs'>
           <Image className='col-1' src={require('@/images/ticket/vip.png')}></Image>
           <Text className='col-2'>退改签享特权！可免服务费 &gt;</Text>
         </View>
         <Image className='col-3' src={require('@/images/ticket/close.png')}></Image>
        </View> */}
        <View className='part-3'>
          <View className='row-1'>购票优惠</View>
          <View className='item'>
            <View className='c-1'>优惠活动</View>
            <View className='c-2' onClick={()=>{
              if(true){
                Taro.$toast('无优惠活动')
                return;
              }
              setShowActicity(true)
            }}>
              <Text className='i-1'>未使用</Text>
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
          <View className='item'>
            <View className='c-1'>优惠券</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-coupon/index?id=${order.id}&type=ticket&seatNum=${order.ticketList?.length}`
              })
            }}>
              {curCoupon.length?<View className="box-flex">
                <Text className='i-3 dot'>{curCoupon.length>1?'多券叠加':curCoupon[0]?.voucherName}</Text>
                <Text style={{margin:'0 8px',fontSize:14}}>-¥{curCoupon?.reduce((acc, cur) => acc + parseFloat(+cur.couponFace), 0)}</Text>
              </View>:<Text className='i-1'>未使用</Text>}
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
        </View>
        <ActivityModal showActivity={showActivity} onClose={()=>{setShowActicity(false)}} />
        {!goodsList.length ? '' :
        <View className='part-5'>
          <View className='row-1'>观影伴侣·美味小食</View>
          <View className='row-2'>
            {goodsList.map(goods => {
              return (
                <View className='item' key={goods.id}>
                  <GoodsItem detail={goods} onChange={changeGoods} count={goodsCount[goods.id] || 0}></GoodsItem>
                </View>
              )
            })}
          </View>
        </View>}
        {goodsTotalCount?
        <View className='part-3' style={{paddingTop:0}}>
          <View className='item'>
            <View className='c-1'>优惠券</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-coupon/index?id=${order.id}&type=goods`
              })
            }}>
              {selectGoodsCoupon.length?<Text className='i-3 dot'>已选择最大优惠</Text>:<Text className='i-1'>未使用</Text>}
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
        </View>:null}
        <View className='part-6'>
          <View className='row-1'>价格明细</View>
          <View className='row'>
            <View className='c-1'>
              <Text className='i-1'>电影票</Text>
              <Text>{order.ticketList.length}张</Text>
            </View>
            <View className='c-2'>
              <Text className='i-1'>¥{priceMap.ticketPrice}</Text>
            </View>
          </View>
          {/* {
            !goodsTotalCount ? '' :
              <View className='row'>
                <View className='c-1'>
                  <Text className='i-1'>美味小食</Text>
                  <Text>{goodsTotalCount}件</Text>
                </View>
                <View className='c-2'>
                  <Text className='i-1'>¥{priceMap.goodsPrice}</Text>
                </View>
              </View>
          } */}
        </View>
        <View className='part-3'>
          <View className='row-1'>支付方式</View>
          <View className='item'>
            <View className='c-1'>电影卡支付</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-card/index?id=${order.id}&cardId=${curCard.id}&price=${priceMap.totalPrice}`
              })
            }}>
              {curCard?.id?<Text>{curCard.cardName}</Text>:<Text className='i-1'>未使用</Text>}
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
          {curCard?.id?<View className="item-p">
            <View>余额：¥{curCard.amount}</View>
            <View>消费余额：¥{RoundNum(priceMap.totalPrice)}</View>
          </View>:null}
          <View className='item'>
            <View className='c-1'>{process.env.TARO_ENV == 'tt'?'抖音支付':'微信支付'}</View>
            <View className='c-2'>
              <Image className='i-2' src={require('@/images/mine/radio-on.svg')}></Image>
            </View>
          </View>
        </View>
        {/* <View className='part-7'>
          <View className='row-1'>购票须知</View>
          <View className='row-2'>
            <View>1.请确认场次和时间无误,购买成功后将不予退换。</View>
            <View>2.由于设备故障等不可抗力因素,存在少量场次取消的情况。</View>
            <View>3.由于网络不稳定因素,存在出票失败的情况,会进行退款。</View>
            <View>4.取票码可以在“我的-电影票”中查看。</View>
          </View>
        </View> */}
      </View>
      <View className='bottom flex-cc'>
        <View className='col-2 flex-cc' onClick={()=>{
          if(curCard?.id){
            setShowModal(true)
            return;
          }
          pay()
        }}>立即支付 ¥{priceMap.totalPrice}</View>
      </View>
      <AtModal className="order-modal" isOpened={showModal} onClose={()=>{setShowModal(false)}}>
        {showModal?<>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowModal(false)}}></View>
          <View className="header-h2">验证卡密码</View>
          <View></View>
        </View>
        <View className="modal-main">
          <View className="main-span" style={{marginBottom:'24px'}}>为了保证你的账号安全，请输入您的会员卡密码后进行下一步操作。</View>
          <YiCode isFocus={showModal} inputType='password' value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>
        <View className="modal-footer">
          <View className="footer-go" onClick={()=>{
            if(captcha.trim()){
              const data = {
                cardId: curCard.id,
                password: captcha,
                type:curCard.isDxCard
              }
              Taro.$post('/cinema-app/api/card/checkPassword',data,'1').then(res=>{
                if(res.code == '1' && res.content){
                  pay()
                }else{
                  setMessageInfo('密码错误')
                  setCaptcha('')
                }
              })
            }
          }}>确认支付 ¥{priceMap.totalPrice}</View>
        </View>
        </>:null}
      </AtModal>
    </View>
  )
}
